<template>
  <div class="uploadArticlePage">
    <div class="row controlBar justify-between">
      <div class="col-12 col-sm searchBarBox">
        <div class="sbTitle text-center"><span>查询</span></div>
        <div class="row searchBar items-center">
          <div class="col-12 col-md-6 col-xl-4 searchItem">
            <div class="row items-center">
              <span class="col-12 col-sm-4">序号:</span>
              <input class="col-12 col-sm-7" v-model="serialNo" />
            </div>
          </div>
          
          <div class="col-12 col-md-6 col-xl-4 searchItem">
            <div class="row items-center">
              <span class="col-12 col-sm-4">设计编号: </span>
              <input class="col-12 col-sm-7" v-model="designNum" />
            </div>
          </div>
          <div class="col-12 col-md-6 col-xl-4 searchItem">
            <div class="row items-center">
              <span class="col-12 col-sm-4">模号:</span>
              <input class="col-12 col-sm-7" v-model="mould" />
            </div>
          </div>
          <div class="col-12 col-md-6 col-xl-4 searchItem">
            <div class="row items-center">
              <span class="col-12 col-sm-4">成色: </span>
              <input class="col-12 col-sm-7" v-model="goldType" />
            </div>
          </div>
          <div class="col-12 col-md-6 col-xl-4  searchItem">
            <div class="row items-center">
              <span class="col-12 col-sm-4">FG Article:</span>
              <input  class="col-12 col-sm-7" v-model="fgArticle" />
            </div>
          </div>
        </div>
        <div class="row searchBtnBox">
          <q-btn color="purple-10" class="searchBtn col-auto" @click="search()"
            >搜寻</q-btn
          >
        </div>
      </div>

      <div class="col-12 col-sm-auto controlBtnBox">
        <div class="row controlBtn">
          <q-btn
            color="warning"
            class="printBtn col"
            label="待新增Article列表"
            @click="exportNCFGArticles()"
          >
            <q-badge color="red" floating v-if="omNum > 0">{{ omNum }}</q-badge>
          </q-btn>
        </div>
        <div class="row controlBtn">
          <q-btn
            color="indigo-5"
            class="printBtn col"
            label="上传档案"
            @click="uploadBox = true"
          >
            <q-icon
              name="fa-solid fa-arrow-up-from-bracket"
              class="uploadSVG"
            />
          </q-btn>
        </div>
        <div class="row controlBtn">
          <q-btn
            color="indigo-10"
            class="printBtn col"
            label="全部导出"
            @click="exportFGArticles()"
          >
            <q-icon name="fa-solid fa-file-arrow-down" class="exportSVG" />
          </q-btn>
        </div>
      </div>
    </div>

    <div v-show="showResult" class="resultTableBox">
      <q-table
        class="resultTable"
        flat
        bordered
        table-header-class="bg-blue-2"
        :rows="rtrows"
        :columns="rtcolumns"
        row-key="serialNo"
        :pagination="{ rowsPerPage: useUploadWo.pagination.rowsPerPage }"
      >
        <template v-slot:header-cell="props">
          <q-th @click="sortByCol(props.col.name)">
            {{ props.col.label }}
            <span v-if="useUploadWo.pagination.sortCol && props.col.name == useUploadWo.pagination.sortCol.replace(/-/g, '')">
              <q-icon
                v-if="useUploadWo.pagination.sortCol[0] == '-'"
                name="arrow_downward"
              ></q-icon>
              <q-icon
                v-if="useUploadWo.pagination.sortCol[0] != '-'"
                name="arrow_upward"
              ></q-icon>
            </span>
          </q-th>
        </template>

        <template v-slot:bottom="scope">
          <q-pagination
            style="margin-right: 5px"
            v-model="useUploadWo.pagination.currentPage"
            color="primary"
            :max="useUploadWo.pagination.max"
            :max-pages="6"
            boundary-numbers
            activeDesign="unelevated"
            activeColor="purple"
          />

          <div style="display: flex; align-items: center; gap: 4px">
            <div style="display: flex; align-items: center; gap: 4px">
              <div>每页的行数:</div>
              <div>
                <q-select
                  dense
                  options-dense
                  borderless
                  optionsCover
                  v-model="scope.pagination.rowsPerPage"
                  :options="[5, 10, 20, 50, 100]"
                  @update:model-value="onchange"
                />
              </div>
              {{
                scope.pagination.rowsPerPage *
                  useUploadWo.pagination.currentPage -
                scope.pagination.rowsPerPage +
                1 +
                " - " +(scope.pagination.rowsPerPage *
                  useUploadWo.pagination.currentPage <=
                useUploadWo.pagination.total
                  ? scope.pagination.rowsPerPage *
                    useUploadWo.pagination.currentPage
                  : rtrows.length) +
                " of " +
                useUploadWo.pagination.total
              }}
            </div>
          </div>
        </template>
        <template v-slot:body-cell-edit="props">
          <q-td :props="props">
            <q-btn
              color="deep-purple-4"
              class="editBtn col"
              label="编辑"
              :disable="props.row.item.length == 0"
              @click="editArticleTb(props.row.master_id)"
            >
              <q-icon name="fa-solid fa-pen" class="editSVG" />
            </q-btn>
          </q-td>
        </template>
      </q-table>
      </div>

      <div class="resultTableBox" v-if="rtrows2.length">
       <q-table
        class="resultTable"
        flat
        bordered
        table-header-class="bg-blue-2"
        :rows="rtrows2"
        :columns="rtcolumns"
        row-key="serialNo"
        :pagination="{ rowsPerPage: useUploadWo.pagination.rowsPerPage }"
      >
        <template v-slot:header-cell="props">
          <q-th @click="sortByCol(props.col.name)">
            {{ props.col.label }}
            <span v-if="useUploadWo.pagination.sortCol && props.col.name == useUploadWo.pagination.sortCol.replace(/-/g, '')">
              <q-icon
                v-if="useUploadWo.pagination.sortCol[0] == '-'"
                name="arrow_downward"
              ></q-icon>
              <q-icon
                v-if="useUploadWo.pagination.sortCol[0] != '-'"
                name="arrow_upward"
              ></q-icon>
            </span>
          </q-th>
        </template>

        <template v-slot:body-cell-edit="props">
          <q-td :props="props">
            <q-btn
              color="deep-purple-4"
              class="editBtn col"
              label="编辑"
              :disable="props.row.item.length == 0"
              @click="editArticleTb(props.row.master_id)"
            >
              <q-icon name="fa-solid fa-pen" class="editSVG" />
            </q-btn>
          </q-td>
        </template>
      </q-table>
    </div>

    <div v-show="showResult && etrows.length > 0" class="resultTableBox">
      <q-table
        class="resultTable"
        flat
        bordered
        table-header-class="bg-red-2"
        :rows="etrows"
        :columns="etcolumns"
        row-key="serialNo"
      >
        <template v-slot:body="props">
          <q-tr :props="props">
            <q-td key="serial" :props="props">
              {{ props.row.serial }}
            </q-td>
            <q-td key="fgArticle" :props="props">
              {{ props.row.fgArticle }}
            </q-td>
            <q-td key="loc" :props="props">
              <div v-for="error in props.row.loc" :key="error.step">
                [{{ error.step }}]
                <span v-for="field in error.fields" :key="field.index"
                  >{{ field }} <br />
                </span>
                <br />
              </div>
            </q-td>
          </q-tr>
        </template>
      </q-table>
    </div>

    <!-- POP UP Window for upload files (choose files) -->
    <q-dialog v-model="uploadBox" class="uploadBox">
      <q-card style="width: 700px; max-width: 80vw" class="uploadCard">
        <q-card-section
          class="row items-center q-pb-none bg-deep-purple-10 text-white"
        >
          <span class="text-h6">上传档案</span>
          <q-space />
          <q-btn icon="close" flat round dense v-close-popup />
        </q-card-section>

        <q-card-section class="text-center" align="center">
          <span class="text-h6"> 请选择一个文件：</span>

          <q-file
            v-model="uploadFiles"
            label="请选择一个文件："
            outlined
            use-chips
            
            accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
            style="max-width: 300px; margin-left: auto; margin-right: auto"
          />
        </q-card-section>
        <q-card-actions align="center">
          <q-btn
            color="deep-purple-5"
            class="uploadBtn"
            label="上传"
            @click="uploadFGArticles()"
          ></q-btn>
        </q-card-actions>
      </q-card>
    </q-dialog>
  </div>
</template>

<script setup>
import { ref, toRaw, watch, reactive } from "vue";
import { useQuasar, Loading, exportFile } from "quasar";
import { useRouter } from "vue-router";
import { useUploadWoStore } from "src/stores/modules/uploadWoFlowStore";

import { exportFGarticle2Excel } from "src/services/reportService";

import * as XLSX from 'xlsjs';

const $router = useRouter();
const $q = useQuasar();
const useUploadWo = useUploadWoStore();

// Search Requirements
const serialNo = ref(null);
const fgArticle = ref(null);
const designNum = ref(null);
const mould = ref(null);
const goldType = ref(null);

// Result
const uploadBox = ref(false);
const uploadFiles = ref(null);
const showResult = ref(true);
const errorItems = ref(null);
const rtrows = ref([]);
let etcolumns = [];
const etrows = ref([]);
let originalTb = [];
let originalTb2 = [];
const rtrows2 = ref([]);

// pagination
// const currentPage = ref(1);
// const rowsPerPage = ref(100);
// const sortCol = ref(null);
// const total = ref(0);
// const max = ref(1);
// const sortDirection = ref('desc');

// Oustanding Master
const omNum = ref(0);
const omLink = ref(null);

// init
const init = async () => {
  const res = await useUploadWo.loadUploadWOPage();
  console.log("res", res);
  if (res) {
    omNum.value = useUploadWo.outstandingNum;
    console.log("onNum: ", omNum.value);
  }
  // test
  // rtrows.value = useUploadWo.fgArticles
};
init();

// Search Result Table columns and rows
const rtcolumns = [
  {
    name: "serial",
    required: true,
    label: "序号",
    align: "center",
    field: (row) => {
      if (row.serial == null){
        return ''
      }
      return row.serial
    },
    format: (val) => `${val}`,
    sortable: true,
  },
  {
    name: "article",
    align: "center",
    label: "FG Article",
    field: "article",
    sortable: true,
  },
  {
    name: "design",
    align: "center",
    label: "设计编号",
    field: "design",
    sortable: true,
  },
  {
    name: "mould",
    align: "center",
    label: "模号",
    field: "mould",
    sortable: true,
  },
  {
    name: "gold",
    align: "center",
    label: "成色",
    field: "gold",
    sortable: true,
  },
  {
    name: "edit",
    align: "center",
    label: "操作",
    field: "edit",
    sortable: false,
  },
];

rtrows.value = [...JSON.parse(JSON.stringify(useUploadWo.createData))];
rtrows2.value = [...JSON.parse(JSON.stringify(useUploadWo.updateData))];

// Error Table
etcolumns = [
  {
    name: "serial",
    required: true,
    label: "序号",
    align: "center",
    field: (row) => row.serial,
    format: (val) => `${val}`,
    sortable: true,
  },
  {
    name: "fgArticle",
    align: "center",
    label: "FG Article",
    field: "fgArticle",
    sortable: true,
  },
  {
    name: "loc",
    align: "center",
    label: "错误",
    field: "loc",
    sortable: false,
  },
];

const compare = reactive({
  state :{
    serial: null,
    fgArticle: null,
    design: null,
    mould: null,
    goldType: null,
  }
})

// Function: Search Function
const search = async () => {
  const searchReq = {
    serial: serialNo.value ? serialNo.value : null,
    fgArticle: fgArticle.value ? fgArticle.value : null,
    design: designNum.value ? designNum.value : null,
    mould: mould.value ? mould.value : null,
    goldType: goldType.value ? goldType.value : null,
    page: useUploadWo.pagination.currentPage,
    rows_per_page: useUploadWo.pagination.rowsPerPage,
    sort_seq: useUploadWo.pagination.sortCol,
  };
  console.log('compare.state.fgArticle', compare.state.fgArticle);
  console.log('searchReq.fgArticle', searchReq.fgArticle);
  if(compare.state.serial!=searchReq.serial ||
    compare.state.fgArticle!=searchReq.fgArticle ||
    compare.state.design!=searchReq.design ||
    compare.state.mould!=searchReq.mould ||
    compare.state.goldType!=searchReq.goldType 
  
  ){
    compare.state.serial = searchReq.serial
    compare.state.fgArticle = searchReq.fgArticle
    compare.state.design = searchReq.design
    compare.state.mould = searchReq.mould
    compare.state.goldType = searchReq.goldType
    searchReq.page = 1
    searchReq.rows_per_page = 10
  }


  const res = await useUploadWo.searchFGarticle(searchReq);
  console.log(res);
  if (res) {
    originalTb = toRaw(useUploadWo.createData);
    originalTb2 = toRaw(useUploadWo.updateData);
    rtrows.value = JSON.parse(JSON.stringify(originalTb));
    rtrows2.value = JSON.parse(JSON.stringify(originalTb2));
    // total.value = res.data.count;
    // max.value = Math.ceil(res.data.count / rowsPerPage.value);
    showResult.value = true;
  } else {
    // error
    $q.notify({
      type: "negative",
      textColor: "white",
      message: "搜寻失败 !",
      timeout: 2000,
      position: "center",
    });
  }
};
watch(
  () => useUploadWo.pagination.currentPage,
  (newCurrentPage) => {
    useUploadWo.pagination.currentPage = newCurrentPage;
    search();
  }
);


function onchange(val) {
  useUploadWo.pagination.rowsPerPage = val;
  useUploadWo.pagination.currentPage = 1;
  search();
}

function sortByCol(col) {
  if (col=='edit') return
  if (useUploadWo.pagination.sortCol==null){
    useUploadWo.pagination.sortCol = col
  }
  useUploadWo.pagination.sortCol = useUploadWo.pagination.sortCol[0] == '-' ? col : '-' +col;
  // useUploadWo.pagination.sortDirection = useUploadWo.pagination.sortDirection == "desc" ? "asc" : "desc";
  search();
}
// FUNCTION: Edit button function
const editArticleTb = (master_id) => {
  $router.push(`/editWOFlow/${master_id}`);
};

// FUNCTION: export not created FG articles
const exportNCFGArticles = async () => {
  const res = await useUploadWo.exportOustandingMaster();
  console.log("res", res);
  if (res) {
    console.log("success");
    omLink.value = useUploadWo.export_os_url;
    console.log("omLink: ", omLink.value);
    window.open(omLink.value);
  } else {
    console.log("fail");
  }
};

// Function: Check if new added Fg articles are already imported
const checkDuplicates = (newRows) => {
  let rtrowsCopy = [...JSON.parse(JSON.stringify(rtrows.value))];

  const removedList = rtrowsCopy.filter(
    (fg) => !newRows.some((e) => e.serial === fg.serial)
  );
  rtrows.value = removedList;
};

const checkDuplicates2 = (newRows) => {
  let rtrowsCopy = [...JSON.parse(JSON.stringify(rtrows2.value))];

  const removedList = rtrowsCopy.filter(
    (fg) => !newRows.some((e) => e.serial === fg.serial)
  );
  rtrows2.value = removedList;
};
// FUNCTION: upload fg article
const uploadFGArticles = async () => {
  const files = uploadFiles.value;

  if (files) {
    const formData = new FormData();
    formData.append("file", files);

    const res = await useUploadWo.uploadFile(formData);
    if (res) {
      // Success
      uploadFiles.value = null;
      let newRows = [];
      let newRows2 = [];
      originalTb = toRaw(useUploadWo.createData);
      originalTb2 = toRaw(useUploadWo.updateData);
      newRows = [...JSON.parse(JSON.stringify(originalTb))];
      newRows2 = [...JSON.parse(JSON.stringify(originalTb2))];
      checkDuplicates(newRows);
      checkDuplicates2(newRows2);
      rtrows.value = rtrows.value.concat(newRows);
      rtrows2.value = rtrows2.value.concat(newRows2);
      // testing
      useUploadWo.updateFGArticle(rtrows.value);
      useUploadWo.updateFGArticle2(rtrows2.value);
      errorItems.value = toRaw(useUploadWo.errorItems);
      etrows.value = [...JSON.parse(JSON.stringify(errorItems.value))];
      uploadBox.value = false;
      showResult.value = true;
    }
  }
};

// FUNCTION: export fg article
const exportFGArticles = async () => {
  console.log("downloading FGArticle file... ");
  // get search req
  const searchReq = {
    serial: serialNo.value ? serialNo.value : null,
    fgArticle: fgArticle.value ? fgArticle.value : null,
    design: designNum.value ? designNum.value : null,
    mould: mould.value ? mould.value : null,
    goldType: goldType.value ? goldType.value : null,
    page: useUploadWo.pagination.currentPage,
    rows_per_page: useUploadWo.pagination.rowsPerPage,
    sort_seq: useUploadWo.pagination.sortCol,
  };

  try {
    Loading.show();
    const res = await exportFGarticle2Excel(searchReq);
    if (res.status == 200) {
      const blob = new Blob([res.data], {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      });
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = 'fgarticle.xlsx';
      link.click();
      URL.revokeObjectURL(link.href);

      if (res.status == 200) {
        $q.notify({
          message: "导出成功",
          color: "positive",
          timeout: 2000,
          position: "center",
        });
      
      } else {
        $q.notify({
          message: "导出失败",
          color: "negative",
          timeout: 2000,
          position: "center",
        });
      }
    }
  } catch (error) {
    console.log(error);
    Loading.hide();
  }
  Loading.hide();
};


</script>

<style lang="scss" scoped>
.uploadArticlePage {
  width: 95%;
  margin-top: 20px;
  margin-left: auto;
  margin-right: auto;
  font-size: 1.2rem;
  @media (max-width: 480px) {
    font-size: 1rem;
  }
  .controlBar {
    background-color: #d8dff4;
    border-radius: 10px;
    padding: 10px 10px 10px 10px;
    width: 100%;
    .searchBarBox {
      background-color: #acbadf;
      padding: 10px 10px 10px 10px;
      margin-right: 3px;
      @media (max-width: 700px) {
        font-size: 1rem;
      }
      .sbTitle {
        width: 100%;
        background-color: rgb(203, 217, 255);
        padding-left: 10px;
        padding-top: 3px;
        font-weight: bold;
        color: #1100bc;
        border-radius: 5px;
      }
      .searchBar {
        padding: 10px 10px 10px 10px;
        .col {
          margin-right: 5px;
        }

        span {
          font-weight: bold;
          margin-right: 5px;
          color: #6727cf;
        }
        .searchItem {
          margin-top: 5px;
        }
      }
      .searchBtnBox {
        width: 100%;
        .searchBtn {
          width: 50%;
          margin-left: auto;
          margin-right: auto;
        }
      }
    }
    .controlBtnBox {
      background-color: #acbadf;
      padding: 10px 10px 10px 10px;
      .controlBtn {
        margin-top: 5px;
        margin-bottom: 5px;
      }
    }

    .uploadSVG,
    .exportSVG {
      margin-left: 10px;
    }
  }
  .resultTableBox {
    margin-top: 10px;

    .editBtn {
      .editSVG {
        font-size: 1rem;
        margin-left: 5px;
      }
    }
  }
}

.articleCheckList {
  font-size: 1rem;
  background-color: #bccbf3;
  border-radius: 5px;
}

::v-deep(.q-table__bottom) {
  justify-content: right !important;
}
</style>
